//
//  TestViewController2.swift
//  Swift表情键盘
//
//  Created by 王冲 on 2018/1/20.
//  Copyright © 2018年 希爱欧科技有限公司. All rights reserved.
//

import UIKit

class TestViewController2: UIViewController {

    
    override func viewDidAppear(_ animated: Bool) {
        
        super.viewDidAppear(animated)
        // 召唤键盘
        textView.becomeFirstResponder()
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        
        super.viewWillAppear(animated)
        // 隐藏键盘
        textView.resignFirstResponder()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.JKRandomColor()
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "打印", style: UIBarButtonItemStyle.plain, target: self, action: #selector(TestViewController2.textContent))
        
        
        // 0.注册通知监听键盘弹出和消失
        NotificationCenter.default.addObserver(self, selector: #selector(TestViewController2.keyboardChange), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        
        // 1.将键盘控制器添加为当前控制器的子控制器
        addChildViewController(jkEmoticonVC)
        
        // 2.消除导航栏的影响
        self.edgesForExtendedLayout = []
        // 3.添加 textView 和 提示内容
        view.addSubview(textView)
        textView.addSubview(placeholderLabel)
        // 4.添加toolBar
        setupToolBar()

    }
    
    /**
     只要键盘改变就会调用
     */
    @objc func keyboardChange(notify: NSNotification)
    {
        print(notify)
        // 1.取出键盘最终的rect
        let value = notify.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
        let rect = value.cgRectValue
        
        // 2.修改工具条的约束
        // 弹出 : Y = 409 height = 258
        // 关闭 : Y = 667 height = 258
        // 667 - 409 = 258
        // 667 - 667 = 0
        
        let duration = notify.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber
        /*
         工具条回弹是因为执行了两次动画, 而系统自带的键盘的动画节奏(曲线) 7
         7在apple API中并没有提供给我们, 但是我们可以使用
         7这种节奏有一个特点: 如果连续执行两次动画, 不管上一次有没有执行完毕, 都会立刻执行下一次
         也就是说上一次可能会被忽略
         
         如果将动画节奏设置为7, 那么动画的时长无论如何都会自动修改为0.5
         
         UIView动画的本质是核心动画, 所以可以给核心动画设置动画节奏
         */
        // 1.取出键盘的动画节奏
        let curve = notify.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber
        
        UIView.animate(withDuration: duration.doubleValue) { () -> Void in
            
            // 2.设置动画节奏
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve.intValue)!)
            self.toolBar.y = rect.origin.y - 64 - 44
        }
        
        let anim = toolBar.layer.animation(forKey: "position")
        print("duration = \(String(describing: anim?.duration))")
    }
    
    deinit
    {
        NotificationCenter.default.removeObserver(self)
        print("销毁自己")
    }
    
    /**
     3.添加底部工具条
     */
    func setupToolBar(){
        
        // 1.添加子控件
        view.addSubview(toolBar)
        
        // 2.添加按钮
        var items = [UIBarButtonItem]()
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "selectPicture"],
                            
                            ["imageName": "compose_mentionbutton_background"],
                            
                            ["imageName": "compose_trendbutton_background"],
                            
                            ["imageName": "compose_emoticonbutton_background", "action": "inputEmoticon"],
                            
                            ["imageName": "compose_addbutton_background"]]
        for dict in itemSettings
        {
            let item = UIBarButtonItem(JKname: dict["imageName"]!, target: self, action: dict["action"])
            items.append(item)
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil))
        }
        
        items.removeLast()
        toolBar.items = items

    }
    
    // MARK: 选择相册
   @objc func selectPicture() {
        
        print("选择相册")
        
    }
    
    // MARK: 切换表情键盘
    @objc func inputEmoticon() {
        
        print("切换表情键盘")
        print(#function)
        // 结论: 如果是系统自带的键盘, 那么inputView = nil
        //      如果不是系统自带的键盘, 那么inputView != nil
        //        print(textView.inputView)
        
        // 1.关闭键盘
        textView.resignFirstResponder()
        
        // 2.设置inputView
        textView.inputView = (textView.inputView == nil) ? jkEmoticonVC.view : nil
        
        // 3.从新召唤出键盘
        textView.becomeFirstResponder()
    }
    
    
    
    // MARK: 内容的输出
    @objc func textContent() {
  
        print(self.textView.emoticonAttr())
   
    }

    // MARK: UITextView 的设置
    lazy var textView: UITextView = {
        
        let textview = UITextView(frame: CGRect(x: 0, y: 0, width: JKscreenW, height: JKscreenH-64))
        textview.delegate = self
        // 垂直水平方向有弹性
        textview.alwaysBounceVertical = true
        // 垂直方向滑动键盘下去
        textview.keyboardDismissMode = UIScrollViewKeyboardDismissMode.onDrag
        textview.font = UIFont.systemFont(ofSize: 20)
        return textview
        
    }()
    
    // MARK: UILabel 提示文本
    lazy var placeholderLabel: UILabel = {
        
        let label = UILabel(frame: CGRect(x: 5, y: 9, width: JKscreenW-10, height: 22))
        label.font = UIFont .systemFont(ofSize: 20)
        label.textColor = UIColor.JKTextGayColor()
        label.text = "分享新鲜事"
        return label
        
    }()
    
    // MARK: 底部的工具条
    private var toolBar: UIToolbar = {
        
        let toolbar = UIToolbar(frame: CGRect(x: 0, y: JKscreenH-64-44, width: JKscreenW, height: 44))
        return toolbar
    }()
    
    /**
     1.weak: 相当于OC里面的__weak, 特点: 是对象释放之后会将变量设置为nil 可选类型
     2.unownd 相当于OC里面的unsafe_unretained, 特点: 对象释放之后不会将变量设置为nil 不可选类型
     */
    lazy var jkEmoticonVC: JKEmoticonViewController = JKEmoticonViewController { [weak self] (emoticon) in
        
        self?.textView.insertEmoticon(emoticon: emoticon)
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

extension TestViewController2: UITextViewDelegate{
    
    func textViewDidChange(_ textView: UITextView) {
        
        print("----------------")
        // 注意点: 输入图片表情的时候不会促发textViewDidChange
        placeholderLabel.isHidden = textView.hasText
        navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
    }
    
}
